/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.aacorps.javaeal.repository.code;

import edu.aacorps.javaeal.common.CodeDTO;
import edu.aacorps.javaeal.repository.BaseRepositoryBean;
import edu.aacorps.javaeal.domain.Code;
import edu.aacorps.javaeal.repository.user.UserRepository;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Ati
 */
@Stateless
public class CodeRepositoryBean extends BaseRepositoryBean<Code, Long> implements CodeRepository {

    @EJB
    private UserRepository userRepository;

    @PersistenceContext(unitName = "edu.aacorps.javaeal_JavaEAL-ejb_ejb_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CodeRepositoryBean() {
        super(Code.class);
    }

    @Override
    public Code find(String code) {
        try {
            return em.createQuery("select c from Code AS c where c.code = :code", Code.class)
                    .setParameter("code", code).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public Code toCodeEntity(CodeDTO codeDTO) {
        Code code = new Code();

        code.setId(codeDTO.getId());
        code.setCode(codeDTO.getCode());
        code.setUser(userRepository.find(codeDTO.getUserName()));

        return code;
    }

    @Override
    public CodeDTO toCodeDTO(Code code) {
        CodeDTO userDTO = new CodeDTO();

        userDTO.setId(code.getId());
        userDTO.setCode(code.getCode());
        userDTO.setUserName(code.getUser().getUserName());

        return userDTO;
    }

}
